﻿using System;
using System.Linq.Expressions;

namespace NMapper.Utils
{
    public static class DefaultValues
    {
        /// <summary>
        /// Though you would think we could just use `Expression.Default`, LinqToSql does not support it.
        /// </summary>
        public static Expression GetDefaultValue(this Type type)
        {
            if (type == typeof(bool))
                return Expression.Constant(false);
            else if (type == typeof(byte))
                return Expression.Constant((byte)0);
            else if (type == typeof(short))
                return Expression.Constant((short)0);
            else if (type == typeof(int))
                return Expression.Constant(0);
            else if (type == typeof(long))
                return Expression.Constant(0L);
            else if (type == typeof(float))
                return Expression.Constant((float)0);
            else if (type == typeof(double))
                return Expression.Constant((double)0);
            else if (type.IsEnum)
                return Expression.Constant(Enum.ToObject(type, GetDefaultValue(Enum.GetUnderlyingType(type))));
            else if (type == typeof(DateTime))
                return Expression.New(
                    type.GetConstructor(new[] { typeof(int), typeof(int), typeof(int) }), 
                    Expression.Constant(1753), Expression.Constant(1), Expression.Constant(1));
            else if (type.IsValueType)
                return Expression.New(type);
            else
                return Expression.Convert(Expression.Constant(null), type);
        }         
    }
}